const asyncSetInterval = async (fn, time = 200) => {
  return new Promise((resolve, reject) => {
    let timer = setInterval(() => {
      let result = fn();
      if (result) {
        clearInterval(timer);
        timer = null;
        resolve(result);
      }
    }, time);
  });
};
// 保存明细表
const saveTableDetail = (tableContent) => {
  window.postMessage(
    {
      event: 'asyncTableDetail',
      data: tableContent
    },
    '*'
  );
};
// 通知主页 申报完成
const currentToTaxindex = (data) => {
  window.postMessage(
    {
      event: 'baoBiaoDetailBack',
      data
      // data: {
      //   step: 1,
      //   isclose: true,  // 是否自动关闭
      //   type: 'zzsYbDetail'
      // }
    },
    '*'
  );
};

const notifications = (data) => {
  window.postMessage(
    {
      event: 'notifications',
      data
    },
    '*'
  );
};

const fixZeroInfo = (data) => {
  window.postMessage(
    {
      event: 'fixZeroInfo',
      data: {
        ...data
      }
    },
    '*'
  );
};

const generateImg = async (ele) => {
  return new Promise((resolve) => {
    window.html2canvas(ele).then(canvas => {
      console.log(canvas.toDataURL());
      resolve(canvas.toDataURL());
    });
  });
};

const asyncTableDetailStartCQ = () => {
  window.postMessage(
    {
      event: 'asyncTableDetailStartCQ'
    },
    '*'
  );
};

const getAsyncTableDetailStartStatus = () => {
  window.postMessage(
    {
      event: 'getAsyncTableDetailStartStatus'
    },
    '*'
  );
};

const getSearchString = (key) => {
  let str = location.search;
  str = str.substring(1, str.length);

  let arr = str.split('&');
  let obj = new Object();

  for (let i = 0; i < arr.length; i++) {
    let tmp_arr = arr[i].split('=');
    obj[decodeURIComponent(tmp_arr[0])] = decodeURIComponent(tmp_arr[1]);
  }
  return obj[key];
};

const zeroReportFail = (data) => {
  window.postMessage(
    {
      event: 'zeroReportFail',
      data
    },
    '*'
  );
};

const closeTabs = (time = 200) => {
  setTimeout(() => {
    window.postMessage(
      {
        event: 'closeTabs'
      },
      '*'
    );
  }, time);
};


export {
  asyncSetInterval,
  saveTableDetail,
  currentToTaxindex,
  notifications,
  fixZeroInfo,
  asyncTableDetailStartCQ,
  getAsyncTableDetailStartStatus,
  getSearchString,
  generateImg,
  zeroReportFail,
  closeTabs
};
